<?php

include_once 'lib/WebServices/Proxy.php';
include_once 'lib/HTML/FormElements.php';

abstract class Controller {
  protected $attributes = array();
  protected $model;
  protected $fe;
  protected $result;
  protected $error = false;
  
  protected function Controller($attr=null){
    foreach($attr as $name=>$val)
      if($val != null) $this->attributes[$name] = htmlspecialchars($val);
    
    $this->fe = new FormElements();
  }
  
  protected function uword($str){
    return ucwords(mb_strtolower($str,'UTF-8'));
  }
  
  protected function checkInput($name, $htmlent=false){
  	if(!strlen(trim($this->attributes[$name])))
      $this->fe->setError($name, 'false');
    else
      $this->attributes[$name] = trim($this->attributes[$name]);
    if($htmlent)
      $this->attributes[$name] = htmlentities($this->attributes[$name], ENT_QUOTES, 'UTF-8');
  }
  
  public function add(){
  	
    $this->error = false;
    
    if($this->model == null)
      throw new MTException('null Model pointer');
      
    try { $this->result = $this->model->add(); }
    catch(MTException $e){  
      $this->error = $e;
      unset($this->result);
    }
    return $this;
  }
  
  public function get(){
  	
    $this->error = false;
    
  	if($this->model == null)
      throw new MTException('null Model pointer');
    
    try { $this->result = $this->model->get(); }
    catch(MTException $e){  
      $this->error = $e;
      unset($this->result);
    }
    return $this;
  }
 
  public function send(){
  	
    if($this->error)
      Proxy::send('<proxy id="response"><error>'.$e->getMessage().'</error></proxy>');
    else
      Proxy::send('<proxy id="response"><result>'.$this->result.'</result></proxy>');
    
  }
  
  public function result(){
  	return $this->error?$this->error:$this->result;
  }
}

?>
